package com.e3.template.tgf;

import java.util.Collections;
import java.util.List;

import com.e3.template.model.TGFFormModel;
import com.e3.web.core.model.SuperModel;
import com.extjs.gxt.ui.client.widget.form.Field;
import com.extjs.gxt.ui.client.widget.form.FieldSet;
import com.extjs.gxt.ui.client.widget.form.FormPanel;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.google.gwt.user.client.Element;

public abstract class TGFGroupsFormPanel<D extends SuperModel> extends TGFFormPanel<D> {
	
	private FormPanel formPanel;
	
	@Override
	protected void onRender(Element parent, int index) {
		super.onRender(parent, index);
		this.setLayout(new FitLayout());
		this.add(getFormPanel());
	}

	private FormPanel getFormPanel() {
		if(formPanel == null){
			List<TGFFormModel> formModels = getFormModels();
			Collections.sort(formModels);
			formPanel = createSingleFormPanel();
			initGroupFormPanel(formPanel, formModels);
		}
		return formPanel;
	}

	protected void initGroupFormPanel(FormPanel fp,List<TGFFormModel> formModels){
		for (TGFFormModel formModel : formModels) {
			FieldSet fieldSet = new FieldSet();
			fieldSet.setTitle(formModel.getName());
			List<Field<?>> fields = formModel.getFields();
			for (Field<?> field : fields) {
				fieldSet.add(field);
			}
			fp.add(fieldSet);
		}
	}
	
	public void clearFormData(){
		getFormPanel().clear();
	}
	
	public abstract List<TGFFormModel> getFormModels();
	
}
